package net.lesscoding.channel;

import lombok.extern.slf4j.Slf4j;
import net.lesscoding.common.Const;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;

/**
 * @author eleven
 * @date 2024/10/21 15:24
 * @apiNote
 */
@Slf4j
public class FileChannelTest {
    @Test
    public void fileChannelTransferToTest() {
        try (FileChannel fromChannel = new FileInputStream(Const.CORE_DATA + "data.txt").getChannel();
             FileChannel toChannel = new FileOutputStream(Const.CORE_DATA + "dataTransferTo.txt").getChannel();) {
            fromChannel.transferTo(0, fromChannel.size(), toChannel);
        } catch (IOException e) {
            log.error("文件输入流通道测试异常", e);
        }
    }

    @Test
    public void fileChannelTransferFromTest() {
        try (FileChannel fromChannel = new FileInputStream(Const.CORE_DATA + "data.txt").getChannel();
             FileChannel toChannel = new FileOutputStream(Const.CORE_DATA + "dataTransferFrom.txt").getChannel();) {
            toChannel.transferFrom(fromChannel,0, fromChannel.size());
        } catch (IOException e) {
            log.error("文件输入流通道测试异常", e);
        }
    }

    /**
     * 分批传输，使用系统的零拷贝来优化传输速度 2G数据
     */
    @Test
    public void quickTransferToTest() {
        try (FileChannel fromChannel = new FileInputStream(Const.CORE_DATA + "data.txt").getChannel();
             FileChannel toChannel = new FileOutputStream(Const.CORE_DATA + "dataTransferTo.txt").getChannel();) {
            long size = fromChannel.size();
            // left代表剩余的字节
            for (long left = size; left > 0;) {
                left -= fromChannel.transferTo((size - left), size, toChannel);
            }
        } catch (IOException e) {
            log.error("文件输入流通道测试异常", e);
        }
    }

    @Test
    public void pathTest() {
        System.out.println(Paths.get("../").getFileName());
    }

}
